package com.lap.generator.domain.template.strategy;

import com.lap.generator.application.assembler.ModelTransformer;
import com.lap.generator.commons.exception.GeneratorException;
import com.lap.generator.commons.tools.FileUtil;
import com.lap.generator.commons.tools.PackageUtil;
import com.lap.generator.domain.CoreFile;
import com.lap.generator.domain.TemplateModel;
import com.lap.generator.domain.template.CodeGenContext;
import com.lap.generator.domain.template.CodeTemplate;
import com.lap.generator.domain.valueobject.CodeType;
import com.lap.generator.infrastructure.persistence.TemplateEngine;
import freemarker.template.TemplateException;

import java.io.IOException;
import java.util.List;

public class QueryPoGen implements CodeTemplate<CoreFile> {
  @Override
  public CodeType getType() {
    return CodeType.DRIVING;
  }

  @Override
  public List<CoreFile> generate(CodeGenContext context) {
    TemplateModel model = ModelTransformer.transform(context.tableMeta(), context.envConfig());
    try {
      TemplateEngine engine = new TemplateEngine();
      String poContent = engine.processTemplate("adapter/driving/QueryPo.java.ftl", model);
      String poPackageName = PackageUtil.pack2Path(model.getBasePackage(), "adapter.driving.query",
          model.getModule(), "po");
      String poFileName = FileUtil.resolverFile("java", model.getClassName(), "QueryPo");
      CoreFile poFile =
          CoreFile.builder()
          .path(poPackageName)
          .fileName(poFileName)
          .content(poContent)
          .build();

      String converterContent = engine.processTemplate("adapter/driving/QueryConverter.java.ftl", model);
      String convertPackageName =
          PackageUtil.pack2Path(model.getBasePackage(), "adapter.driving.query", model.getModule());
      String converterName = FileUtil.resolverFile("java", model.getClassName(), "QueryConverter");
      CoreFile convertFile = 
          CoreFile.builder()
          .path(convertPackageName)
          .fileName(converterName)
          .content(converterContent)
          .build();

      return List.of(poFile, convertFile);
    } catch (IOException | TemplateException e) {
      throw new GeneratorException("Po engine error:", e);
    }
  }
}
